package com.ruoyi.auth.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.auth.form.MiniProgramLoginBody;
import com.ruoyi.auth.service.MiniProgramLoginService;
import com.ruoyi.auth.service.RemoteWxLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.factory.RemoteUserFallbackFactory;
import com.ruoyi.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("bank")
public class BankTokenController {
    private static final Logger log = LoggerFactory.getLogger(BankTokenController.class);

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MiniProgramLoginService loginService;

    @Autowired
    private RemoteWxLoginService wxLoginService;

    public static final String appId = "wx160268c0ccaf1846";
    public static final String secret = "05985cea784a4a02520297a1fd8a2ee1";


    @PostMapping("login")
    public R<?> login(@RequestBody MiniProgramLoginBody form) {
        String respDesc = wxLoginService.login(appId, secret, form.getCode(), "authorization_code");
        log.info("wx登录请求结果：{}", respDesc);
        Map<String,Object> resp = JSON.parseObject(respDesc, Map.class);
        if (resp.get("openid") != null) {
            LoginUser userInfo = loginService.login(resp.get("openid").toString());
            return R.ok(tokenService.createToken(userInfo));
        } else {
            if ((int) resp.get("errcode") == 40029) {
                return R.fail(401,"code 无效");
            } else if ((int) resp.get("errcode") == 45011) {
                return R.fail(403,"频率限制，每个用户每分钟100次");
            } else if ((int) resp.get("errcode") == -1) {
                return R.fail(503,"微信系统繁忙，稍候再试");
            } else {
                return R.fail(resp);
            }
        }
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            loginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

}
